package ldh.im.util;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class JsonUtil {

    private static String DATETIME_FORMATTER_STR = "yyyy-MM-dd HH:mm:ss";
    private static String DATE_FORMATTER_STR = "yyyy-MM-dd";
    private static DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern( DATETIME_FORMATTER_STR);
    private static DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern( DATE_FORMATTER_STR);
    //序列化
    final static JsonSerializer<LocalDateTime> jsonSerializerDateTime = (localDateTime, type, jsonSerializationContext) -> new JsonPrimitive(localDateTime.format(DATETIME_FORMATTER));
    final static JsonSerializer<LocalDate> jsonSerializerDate = (localDate, type, jsonSerializationContext) -> new JsonPrimitive(localDate.format(DATE_FORMATTER));
    //反序列化
    final static JsonDeserializer<LocalDateTime> jsonDeserializerDateTime = (jsonElement, type, jsonDeserializationContext) -> LocalDateTime.parse(jsonElement.getAsJsonPrimitive().getAsString(), DATETIME_FORMATTER);
    final static JsonDeserializer<LocalDate> jsonDeserializerDate = (jsonElement, type, jsonDeserializationContext) -> LocalDate.parse(jsonElement.getAsJsonPrimitive().getAsString(), DATE_FORMATTER);


    public static String toJson(Object obj) {
        Gson gson = buildGson();
        return gson.toJson(obj);
    }

    public static<T> T toObject(String json, Type type) {
        Gson gson = buildGson();
        return gson.fromJson(json, type);
    }

    public static<T> T toObject(String json, Class<T> clazz) {
        Gson gson = buildGson();
        return gson.fromJson(json, clazz);
    }

    private static Gson buildGson() {
        Gson gson = new GsonBuilder()
                .setPrettyPrinting()
                .setDateFormat(DATETIME_FORMATTER_STR)
                .registerTypeAdapter(LocalDateTime.class, jsonSerializerDateTime)
                .registerTypeAdapter(LocalDate.class, jsonSerializerDate)
                .registerTypeAdapter(LocalDateTime.class, jsonDeserializerDateTime)
                .registerTypeAdapter(LocalDate.class, jsonDeserializerDate)
                .registerTypeAdapter(LocalDateTime.class,new LocalDateTimeAdapter())
                .create();
        return gson;
    }
}
